<?php
namespace app\admin\controller;
//use Workerman\Worker;
use  think\Db;
class Order extends SessionCheck
{
    public function index()
    {
		$aid = input('get.aid');
		$order_id = input('get.order_id');
		$where = '';
		if(!empty($aid)){
			$where['aid'] = $aid;
		}
		if(!empty($order_id)){
			$where['order_id'] = $order_id;
		}
		$pages = pages('order',$where,input('get.page'));
		$data = Db::table("order")->where($where)->whereIn('aid',session('aid'))->limit($pages['limit'])->order('id desc')->select();
                
        return view('',['data'  => $data,'pages' => $pages['pages'],'menu_list'=>$this->menu_list]);
    }
	
      public function del()
      {
		$id = input("get.id")?input("get.id"):0;
		$page = input("get.page");
		Db::table("order")->whereIn('aid',session('aid'))->delete($id);
		redirect(url('/admin/order').'?page='.$page);
		exit;
      }

    public function detail()
    {
        $order_id = input("get.order_id")?input("get.order_id"):0;
        $data = Db::table('order')->where('order_id',$order_id)->find();
        $goods = Db::table('order_goods')->where('order_id',$order_id)->select();
        foreach ($goods as $k => $v){
            $goods_info = Db::table('service')->where('id',$v['goods_id'])->find();
            $goods[$k]['price'] = $goods_info['price'];
            $goods[$k]['image'] = $goods_info['image1'];
            $goods[$k]['title'] = $goods_info['title'];
        }
        $data['goods'] = $goods;
        return view('',['data'=>$data]);
    }

    public function setting()
    {
        $tab = input("get.tab");
        if(request()->isPost()){
            $data = request()->post();
            $type = request()->request('type');
            if($type == 'alipay'){
                Db::table("payment")->where(['id'=>1])->update($data);
            }else{
                file_get_contents(APP_PATH."../vendor/wxpayv_app/apiclient_cert.pem",$data['apiclient_cert']);
                file_get_contents(APP_PATH."../vendor/wxpayv_app/apiclient_key.pem",$data['apiclient_key']);
                unset($data['apiclient_cert']);
                unset($data['apiclient_key']);
                Db::table('wxpay')->where('type','app')->update($data);
            }
            $this->redirect(url('order/setting').'?tab='.$tab);
            exit;
        }
        $wxdata = Db::table('wxpay')->where('type','app')->order('id desc')->find();
        $data = Db::table("payment")->find();
        $apiclient_cert = file_get_contents(APP_PATH."../vendor/wxpayv_app/apiclient_cert.pem");
        $apiclient_key = file_get_contents(APP_PATH."../vendor/wxpayv_app/apiclient_key.pem");
        return view('',['data' => $data,'wxdata'=>$wxdata,'tab' => $tab,'apiclient_cert'=>$apiclient_cert,'apiclient_key'=>$apiclient_key,'menu_list'=>$this->menu_list]);
    }

    //调度系统汇总
    public function dispatch()
    {
        $this_time = time();
        $aid = request()->get('aid');
        $order_id = request()->request('order_id');
        $order = Db::table('order')->where('order_id',$order_id)->find();
        if(request()->isPost()){
            $msg['state'] = 0;
            if(!empty($order['express'])){
                $msg['msg'] = '调度失败，已被配送员接单';
            }else{
               if($order['status'] !=1){
                   $msg['msg'] = '无法调度，订单状态已改变';
                }else{
                    $uid = request()->request('uid');
                    $express =  Db::table('user')->where('id',$uid)->find();
                    if($express['business'] == 1 && ($express['active_time']+300)> $this_time){
                        $msg['state'] = 1;
                        $data['express_get_money'] = ($order['express_charge']-($order['express_charge']*($express['express_cut']/100)))+($order['tip']-($order['tip']*($express['tip_cut']/100)));
                        $data['express'] = $uid;
                        $data['status'] = 3;
                        Db::table('order')->where('order_id',$order_id)->update($data);
                        //push 配送 被调度
                        push(md5($uid),json_encode(['type'=>2,'message'=>'您有一条私人订单，请及时处理','parameters'=>$order_id,'status'=>7]));
                        insert_message($uid,'订单提醒','您有一条私人订单，请及时处理',7,$order_id);

                        //push 用户
                        push(md5($order['uid']),json_encode(['type'=>1,'message'=>'您的订单已被配送员接单','parameters'=>$order_id,'status'=>5]));
                        insert_message($uid,'订单提醒','您的订单已被配送员接单',5,$order_id);

                        $msg['msg'] = '分配成功';
                    }else{
                        $msg['msg'] = '配送员暂时不在线，无法派单';
                    }
                }
            }
            return json($msg);
        }else{
            $order_id = request()->get('order_id');
            if($order_id != ''){
                $express_id = request()->get('express_id');
                $where['isExpress'] = 1;
                $where['business'] = 1;
                if(!empty($express_id)){
                    $where['id'] = ['<>',$express_id];
                }
                if(!empty($order['place_lng']) && !empty($order['place_lat'])){
                    $center['lng'] = $order['place_lng'];
                    $center['lat'] = $order['place_lat'];
                }else{
                    $center['lng'] = $order['target_lng'];
                    $center['lat'] = $order['target_lat'];
                }

                $express = Db::table('user')->where($where)->where('active_time>'.($this_time-300))->whereIn('aid',session('aid'))->select();
                $express_info = Db::table('user')->where(['id'=>$express_id,'isExpress'=>1])->find();
                if(count($express_info) > 0){
                    $express[count($express)] = $express_info;
                }
                $express_str = '';

                foreach ($express as $v){
                    $express_type = Db::table('express_type')->where('id',$v['express_type'])->value('name');
                    $count = Db::table('order')->where(['express'=>$v['id'],'status'=>3])->count();
                    if($v['lng']){
                        $express_str .= $v['lng'].','.$v['lat'].','.$express_type.'-'.$v['true_name'].','.$count.','.$v['id'].'&';
                    }
                }
                if($aid){
                    $icon = Db::table('express_config')->where('aid',$aid)->value('express_icon');
                }else{
                    $icon = Db::table('express_config')->value('express_icon');
                }
                $express_str = substr($express_str,0,strlen($express_str)-1);
                return view('',['express_str'=>$express_str,'center'=>$center,'order_id'=>$order_id,'icon'=>$icon]);
            }else{
                $where = [];
                if(!empty($aid)){
                    $where['aid'] = $aid;
                }
                $type = request()->get('type');
                if($type == 'express'){
                    $where['express_type'] = ['<>',0];
                    $pages = pages('user',$where,input('get.page'));
                    $data = Db::table('user')->where($where)->whereIn('aid',session('aid'))->limit($pages['limit'])->order('status desc,active_time desc')->select();
                    foreach ($data as $k => $v){
                        if((($v['active_time']+300)>$this_time) && $v['business'] == 1||$v['express_type']==2){
                            $data[$k]['active'] = true;
                        }else{
                            $data[$k]['active'] = false;
                        }
                        $data[$k]['express_type_name'] = Db::table('express_type')->where('id',$v['express_type'])->value('name');
                    }
                    return view('dispatch_express',['data' => $data,'pages' => $pages['pages']]);
                }elseif($type == 'order'){
                    $where['status'] = 1;
                    $pages = pages('order',$where,input('get.page'));
                    $data = Db::table("order")->where($where)->whereIn('aid',session('aid'))->limit($pages['limit'])->order('id desc')->select();
                    return view('dispatch_order',['data' => $data,'pages' => $pages['pages']]);
                }else{
                    return view('dispatch_system');
                }
            }
        }
    }

    public function send_order()
    {
        $tab = (string)request()->get('tab');
        return view('send_order_' . $tab);
    }

    public function socket()
    {
        $aid = (int)request()->get('aid');
        if(!empty($aid)){
            $where['aid'] = $aid;
        }
        $type = request()->get('type');
        if($type == 'order'){
            $where['status'] = 2;
            $pages = pages('order',$where,input('get.page'));
            $data = Db::table("order")->where($where)->whereIn('aid',session('aid'))->limit($pages['limit'])->order('id desc')->select();
        }elseif($type == 'express'){
            $this_time = time();
            $where['express_type'] = ['<>',0];
            $pages = pages('user',$where,input('get.page'));
            $data = Db::table('user')->where($where)->whereIn('aid',session('aid'))->limit($pages['limit'])->order('status desc,active_time desc')->select();
            foreach ($data as $k => $v){
                if(($v['active_time']+300)>$this_time && $v['business'] == 1||$v['express_type']==2){
                    $data[$k]['active'] = true;
                }else{
                    $data[$k]['active'] = false;
                }
                $data[$k]['express_type_name'] = Db::table('express_type')->where('id',$v['express_type'])->value('name');
            }
        }
        return count($data);
    }
    /***系统抽成财务明细***/
    public function finance(){
      $where=[];   
      $aid=request()->request("aid");//地区 
      if(!empty($aid)){
         $where['aid']=$aid;
      }
      $pages = pages('system_money',$where, input('get.page'));//分页
      //
      $data=Db::table("system_money")->where($where)->whereIn('aid', session('aid'))->limit($pages['limit'])->order('id desc')->select();
      foreach($data as $k=>$v){
        if(!empty($v['aid'])||!empty($v['cid'])||!empty($v['pid'])){
            $area=Db::table("area")->where('id',$v['aid'])->value("name");
            $city=Db::table("city")->where('id',$v['cid'])->value("name");
            $province=Db::table("province")->where('id',$v['pid'])->value("name");
            $data[$k]['area']=$area;
            $data[$k]['city']=$city;
            $data[$k]['province']=$province;
         }else{
            $data[$k]['area']='';//不存在就为空
            $data[$k]['city']='';
            $data[$k]['province']='';
         }     
       }
       //往网页渲染
      return view('', ['data' => $data, 'pages' => $pages['pages'], 'menu_list' => $this->menu_list]);
    }
    

}
